<?php
/**
 * Created by PhpStorm.
 * User:tsingStar
 * Date: 2019/7/27
 * Time: 15:28
 */

namespace app\home\controller;


class Chat extends Common
{
    protected function _initialize()
    {
        parent::_initialize();
        if(!session("user_id")){
            $this->redirect("Index/login");
        }
    }

    /**
     * 聊天
     */
    public function index()
    {

        $this->templateTitle("客服");
        //获取最近三小时聊天记录
        $list = db("message")->where("send_id=".session("user_id")." or receive_id=".session("user_id"))->where("create_time", ">", time()-30*24*60*60)->order("create_time asc")->select();
        $this->assign("list", $list);
        $user = \app\common\model\User::exists(session("user_id"));
        $this->assign("avatar", $user["avatar"]);
        $this->assign("logo", "/static/home/images/avatar.png");
        //最后一条聊天记录
        $last_id = db("message")->where("send_id=".session("user_id")." or receive_id=".session("user_id"))->order("create_time desc")->value("id");
        $this->assign("last_id", empty($last_id)?0:$last_id);
        return $this->fetch("index");
    }
    /*
     * 发送消息
     */
    public function send_msg()
    {
        $uid = session("user_id");
        $content = input("con");
        $type = input("type");
        if($content == ""){
            $this->ajaxError("消息不能为空");
        }
        $res = db("message")->insertGetId([
            "send_id"=>$uid,
            "receive_id"=>0,
            "content"=>$content,
            "type"=>$type,
            "create_time"=>time()
        ]);
        if($res){
            $this->ajaxSuccess("发送成功", $res);
        }else{
            $this->ajaxError("发送失败");
        }
    }

    /**
     * 获取聊天记录
     */
    public function getChatList()
    {
        $last_id  = input("last_id");
        $list = db("message")->where("id", ">", $last_id)->where("receive_id", session("user_id"))->select();
        $l_id = db("message")->where("id", ">", $last_id)->where("receive_id", session("user_id"))->order("id desc")->value("id");
        $this->ajaxSuccess('', ['last_id'=>$l_id, 'msg_data'=>$list]);
    }
    

}